package com.itheima.netty.protocol;

import java.util.List;
import java.util.Map.Entry;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;


/**
 * 消息编解码
 * @author ezqinwa
 *
 */

public class NettyMessageEncoder extends MessageToMessageEncoder<NettyMessage> {

	 NettyMarshallingEncoder marshallingEncoder;
	
	public NettyMessageEncoder() throws Exception {
		this.marshallingEncoder = MarshallingCodeCFactory.buildMarshallingEncoder();
	}
	
	@Override
	protected void encode(ChannelHandlerContext ctx, NettyMessage msg, List<Object> out) throws Exception {
		
		if(msg == null || msg.getHeader() == null){
			throw new Exception("The encode ,message is null");
		}
		
		ByteBuf sendbuffer = Unpooled.buffer();
		sendbuffer.writeInt(msg.getHeader().getCrcCode());
		sendbuffer.writeInt(msg.getHeader().getLength());
		sendbuffer.writeLong(msg.getHeader().getSessionId());
		sendbuffer.writeByte(msg.getHeader().getType());
		sendbuffer.writeByte(msg.getHeader().getPriority());
		sendbuffer.writeInt(msg.getHeader().getAttachment().size());
		
		String key = null;
		byte[] keyArray = null;
		Object value = null;
		for (Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) {
			
			key = param.getKey();
			keyArray = key.getBytes("UTF-8");
			sendbuffer.writeInt(keyArray.length);
			sendbuffer.writeBytes(keyArray);
			value = param.getValue();
			marshallingEncoder.encode(ctx, value,sendbuffer);
		}
		
		if(msg.getBody() != null){
			marshallingEncoder.encode(ctx,msg.getBody(), sendbuffer);
		}else{
			sendbuffer.writeInt(0);
			sendbuffer.setInt(4, sendbuffer.readableBytes());
		}
	}

}
